#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('playlist_extractor.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)

class PlaylistExtractor:
    def __init__(self, music_dir):
        self.music_dir = music_dir
        
    def find_music_files(self):
        """查找目录下所有音乐文件"""
        music_files = []
        # 支持的音乐文件格式
        supported_formats = ['.ncm', '.mp3', '.flac', '.wav', '.m4a']
        
        for root, dirs, files in os.walk(self.music_dir):
            for file in files:
                if any(file.lower().endswith(ext) for ext in supported_formats):
                    music_files.append(os.path.join(root, file))
        return music_files
    
    def extract_song_info(self, file_path):
        """从音乐文件名提取歌曲信息"""
        # 获取文件名（不含扩展名）
        filename = os.path.basename(file_path)
        
        # 移除文件扩展名
        extensions = ['.ncm', '.mp3', '.flac', '.wav', '.m4a']
        song_info = filename
        for ext in extensions:
            if song_info.lower().endswith(ext):
                song_info = song_info[:-len(ext)]
                break
                
        return song_info
    
    def generate_playlist(self):
        """生成歌单"""
        music_files = self.find_music_files()
        logging.info(f"找到 {len(music_files)} 个音乐文件")
        
        if not music_files:
            logging.info("没有找到音乐文件")
            return []
            
        playlist = []
        
        for i, music_file in enumerate(music_files, 1):
            try:
                # 从文件名提取歌曲信息
                song_info = self.extract_song_info(music_file)
                playlist.append(song_info)
                logging.info(f"进度: {i}/{len(music_files)} - {song_info}")
                
            except Exception as e:
                logging.error(f"处理文件 {music_file} 时出错: {e}")
        
        logging.info(f"歌单生成完成! 共 {len(playlist)} 首歌曲")
        return playlist
    
    def save_playlist(self, playlist, output_file='playlist.txt'):
        """保存歌单到文件"""
        if not playlist:
            logging.warning("没有数据可保存")
            return
            
        try:
            # 对歌单进行排序
            sorted_playlist = sorted(playlist, key=lambda x: x.lower())
            
            with open(output_file, 'w', encoding='utf-8') as f:
                for i, song in enumerate(sorted_playlist, 1):
                    f.write(f"{i}. {song}\n")
            
            logging.info(f"歌单已保存到 {output_file} (已排序)")
            
            # 同时保存纯歌单格式（歌名-歌手）
            pure_playlist_file = output_file.replace('.txt', '_pure.txt')
            with open(pure_playlist_file, 'w', encoding='utf-8') as f:
                for song in sorted_playlist:
                    f.write(f"{song}\n")
            
            logging.info(f"纯歌单已保存到 {pure_playlist_file} (已排序)")
            
        except Exception as e:
            logging.error(f"保存歌单时出错: {e}")

def main():
    import argparse
    
    # 解析命令行参数
    parser = argparse.ArgumentParser(description='提取.ncm文件歌单')
    parser.add_argument('--music_dir', default='/Users/lijun/Library/Mobile Documents/com~apple~CloudDocs/Music', 
                       help='音乐文件目录')
    parser.add_argument('--output_file', default='playlist.txt', help='输出文件路径')
    
    args = parser.parse_args()
    
    # 检查音乐目录是否存在
    if not os.path.exists(args.music_dir):
        logging.error(f"音乐目录不存在: {args.music_dir}")
        return
    
    # 创建提取器实例
    extractor = PlaylistExtractor(args.music_dir)
    
    # 生成歌单
    playlist = extractor.generate_playlist()
    
    # 保存歌单
    extractor.save_playlist(playlist, args.output_file)

if __name__ == "__main__":
    main()